/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.exception.diagnostic.initializer;

import io.iec.edp.caf.commons.exception.diagnostic.exception.DataSourceCreationException;
import io.iec.edp.caf.commons.utils.StringUtils;
import lombok.var;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.util.Map;

/**
 * 在上下文的初始里检查数据源是否完整
 * @author wangyandong
 * @date 2021/09/26 17:13
 * @email wangyandong@inspur.com
 */
public class DataSourceInitializer implements ApplicationContextInitializer {
    /**
     * Initialize the given application context.
     *
     * @param applicationContext the application to configure
     */
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        Environment env = applicationContext.getEnvironment();
        //这里因为配置中心会走两遍，cloud走一遍，boot走一遍，cloud里过来，此Property被赋值，boot里不被赋值，cloud和boot里的env不是同一个
        var loaded = env.getProperty("caf.config.client");
        if(loaded==null){
            if(StringUtils.isEmpty(env.getProperty("spring.datasource.url"))){
                throw new DataSourceCreationException("数据源配置不完整：url为空");
            }

            if(StringUtils.isEmpty(env.getProperty("spring.datasource.url"))){
                throw new DataSourceCreationException("数据源配置不完整：用户名user为空");
            }

            if(StringUtils.isEmpty(env.getProperty("spring.datasource.url"))){
                throw new DataSourceCreationException("数据源配置不完整：密码password为空");
            }
        }

    }
}
